<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- PageTools全局组件区域 -->
      <PageTools :show-before="true">
        <template v-slot:before>
          <span>共{{ page.total }}条记录</span>
        </template>
        <template v-slot:after>
          <el-button
            size="small"
            type="warning"
            @click="$router.push('/import')"
            >导入</el-button
          >
          <el-button size="small" type="danger" @click="exportData"
            >导出</el-button
          >
          <el-button
            :disabled="!checkPermission('ADD_USER')"
            size="small"
            type="primary"
            @click="showDialog = true"
            >新增员工</el-button
          >
        </template>
      </PageTools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table :border="true" :data="list">
          <el-table-column label="序号" :sortable="true" type="index" />
          <el-table-column label="姓名" :sortable="true" prop="username" />/
          <el-table-column
            label="头像"
            :sortable="true"
            prop="username"
            align="center"
            style="width: 120px; height: 120px"
          >
            <template v-slot="{ row }">
              <img
                v-imagerror="require('@/assets/common/img.jpeg')"
                :src="row.staffPhoto"
                alt=""
                style="border-radius: 50%; height: 100px; width: 100px"
                @click="showQrCode(row.staffPhoto)"
              />
            </template>
          </el-table-column>
          <el-table-column label="工号" :sortable="true" prop="workNumber" />
          <el-table-column
            label="聘用形式"
            :formatter="formatEmployment"
            :sortable="true"
            prop="formOfEmployment"
          />
          <el-table-column
            label="部门"
            :sortable="true"
            prop="departmentName"
          />
          <el-table-column label="入职时间" :sortable="true">
            <template v-slot="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" :sortable="true" prop="enableState">
            <template v-slot="{ row }">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            :sortable="true"
            fixed="right"
            width="280"
          >
            <template v-slot="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/detail/${row.id}`)"
                >查看
              </el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)"
                >角色</el-button
              >
              <el-button type="text" size="small" @click="delEmployee(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :page-size="page.size"
            :current-page="page.page"
            :total="page.total"
            @current-change="changePage"
            layout="prev, pager, next"
          />
        </el-row>
      </el-card>
      <!-- 新增员工弹层 -->
      <!-- sync修饰符 这里的sync修饰符可以让子组件自己直接修改此数据 -->
      <AddEmployee :showDialog.sync="showDialog"></AddEmployee>
      <el-dialog title="二维码" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <!-- 对话框中有一个canvas画布用来画二维码 -->
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>

      <assignRole
        :showRoleDialog.sync="showRoleDialog"
        :userId="userId"
        ref="assignRole"
      ></assignRole>
    </div>
  </div>
</template>

<script>
import { getEmployeeListAPI, delEmployeeAPI } from "@/api/employees";
import EmployeeEnum from "@/api/constant/employees";
import AddEmployee from "./components/add-employee.vue";
import { formatDate } from "@/filters";
import QrCode from "qrcode";
import assignRole from "./components/assign-role.vue";
export default {
  components: { AddEmployee, assignRole },
  data() {
    return {
      loading: false,
      list: [], // 接数据的
      page: {
        page: 1, // 当前页码
        size: 10,
        total: 0, // 总数
      },
      showDialog: false,
      showCodeDialog: false,
      // 分配角色管理 数据
      showRoleDialog: false,
      userId: null,
    };
  },
  created() {
    this.getEmployeeList();
  },
  methods: {
    async getEmployeeList() {
      this.loading = true;
      const { rows, total } = await getEmployeeListAPI(this.page);
      this.list = rows;
      this.page.total = total;
      this.loading = false;
    },
    changePage(newPage) {
      this.page.page = newPage;
      this.getEmployeeList();
    },
    // 格式化聘用形式
    // row：当前这一行的数据对象
    // column： 当前这一列的对象
    // cellValue： 当前单元格的值
    // index: 索引
    formatEmployment(row, column, cellValue, index) {
      // 要去找 1所对应的值 （hireType：聘用形式）
      const obj = EmployeeEnum.hireType.find((item) => item.id === cellValue);
      return obj ? obj.value : "未知";
    },
    // 删除员工回调
    delEmployee(id) {
      this.$confirm("您确定删除该员工吗?", "确认信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await delEmployeeAPI(id);
          this.getEmployeeList();
          this.$message.success("删除成功!");
        })
        .catch((error) => {
          this.$message.info(error || "已取消");
        });
    },
    // 导出excel数据
    exportData() {
      // 表头
      const headers = {
        姓名: "username",
        手机号: "mobile",
        入职日期: "timeOfEntry",
        聘用形式: "formOfEmployment",
        转正日期: "correctionTime",
        工号: "workNumber",
        部门: "departmentName",
      };
      import("@/vendor/Export2Excel").then(async (excel) => {
        const { rows } = await getEmployeeListAPI({
          page: 1,
          size: this.page.total,
        });

        // 格式化数据
        const data = this.formatJson(headers, rows);
        // 复杂表头的部分
        const multiHeader = [["姓名", "主要信息", "", "", "", "", "部门"]];
        // 需要合并的部分
        const merges = ["A1:A2", "B1:F1", "G1:G2"];

        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          autoWidth: true,
          bookType: "xlsx",
          filename: "员工信息表",
          multiHeader, // 复杂表头
          merges, // 合并选项
        });
      });
    },
    // 该方法负责将数组转化成二维数组
    // 格式化数据的回调
    formatJson(headers, rows) {
      return rows.map((item) => {
        return Object.keys(headers).map((key) => {
          if (
            headers[key] === "timeOfEntry" ||
            headers[key] === "correctionTime"
          ) {
            return formatDate(item[headers[key]]);
          } else if (headers[key] === "formOfEmployment") {
            const obj = EmployeeEnum.hireType.find(
              (obj) => obj.id === item[headers[key]]
            );
            return obj ? obj.value : "未知";
          }
          return item[headers[key]];
        });
      });
    },
    // 点击弹出 二维码的回调
    showQrCode(url) {
      if (url) {
        this.showCodeDialog = true;
        // 下一次DOM更新后在执行
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.myCanvas, url); // 将地址转化成二维码
        });
      } else {
        this.$message.warning("该用户还未上传头像!");
      }
    },
    // 角色按钮 回调函数
    async editRole(id) {
      this.userId = id;
      await this.$refs.assignRole.getUserDetailById(id);
      this.showRoleDialog = true;
    },
  },
};
</script>

<style>
</style>